const fs = require('fs')
const Promise = require('bluebird')
const path = require('path')
const mongoose = require('../db/db')

//在这里挂载所有模型
function initialize() {
    // 存放所有的加载模型函数
    var loadModelAsynFns = new Array();
    // 获取映射文件路径
    var modelsPath = path.join(process.cwd(), "/models");
    // 读取所有模型文件
    var files = fs.readdirSync(modelsPath);
    if(!files) {
        console.log('未找到模型文件')
        return;
    }
    files.forEach(file => {
        var modelName = file.substring(0, file.indexOf('.'));//模型名称
        var requirePath = modelsPath + "\\" + modelName;//引用路径
        var modelInfo = require(requirePath);
        var schema = new mongoose.Schema(modelInfo);//新建schema
        loadModelAsynFns[modelName]=mongoose.model(modelName, schema)//生成模型并加入数组
    });
    global.database = loadModelAsynFns;
}

module.exports.initialize = initialize;
module.exports.getDatabase = function () {
    return global.database;
}